#include "key.h"

uint8_t Key_read(void)
{
    if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0) == 0)
        return  1;
    else if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_1) == 0)
        return  2;
    else if (HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_2) == 0)
        return  3;
    else if (HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_0) == 0)
        return  4;
    else
        return 0;
}

uint32_t five_time_old;
uint32_t five_time_led_old;
uint8_t pass;//密码正确，通过
uint8_t error_count;//错误大于等于3次
uint8_t confirm;//确定
uint8_t key_now, key_up, key_down, key_old;
void Key_proc(void)
{
    key_now = Key_read();
    key_down = key_now & (key_now ^ key_old);
    key_old = key_now;

    if(key_down)
        
        {//uled[key_down] ^= 1;
            switch (key_down)
            {
            case 1:if(show_mode==0)
            {
                              pass_word[0] += 1;
                if (pass_word[0]>'9')
                    pass_word[0] = '0';  
            }


                        break;
            case 2:
                if (show_mode == 0)
                {
                    pass_word[1] += 1;
                if (pass_word[1] > '9')
                    pass_word[1] = '0';
                }

                break;
            case 3:
                if (show_mode == 0)
                {
                                        pass_word[2] += 1;
                if (pass_word[2] > '9')
                    pass_word[2] = '0';
                }

                break;
            case 4:
                if (show_mode == 0)
                    confirm = 1;
                break;
            default:
                break;
            }
        }

        if(confirm == 1)
        {
            if (pass_word[0] == pass_word_true[0] && pass_word[1] == pass_word_true[1] && pass_word[2] == pass_word_true[2])
            {
                pass = 1;
                five_time_old=HAL_GetTick();
                show_mode = 1;
                error_count = 0;
            }
            else
            {
                error_count++;
                if(error_count>=3)
                {
                    five_time_led_old = HAL_GetTick();
                }
                pass = 0;
                show_mode = 0;
                for (uint8_t i = 0; i < 3;i++)
                    pass_word[i] = '@';
            }
            confirm = 0;
        }
}


void Five_second_proc(void)
{
    if(pass == 1)
    {
        uint32_t five_time_now = HAL_GetTick();
        if (five_time_now >= five_time_old + 5000)
        {
            Freq = 1000;
            duty = 50;
            pass = 0;
            for (uint8_t i = 0; i < 3; i++)
                pass_word[i] = '@';
        }
        else
        {
            Freq = 2000;
            duty = 10;
            uled[0] = 1;
        }
    }
    else
    {
        show_mode = 0;
        uled[0] = 0;
    }
}